package action;

import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Map;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import util.BeanUtil;
import bean.XmlBean;
public class ActionServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	  
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,IOException{
		String path = this.getPath(request.getServletPath());
		Map<String, XmlBean> map = (Map<String, XmlBean>) this.getServletContext().getAttribute("struts");
		XmlBean xml = map.get(path.substring(1));
		String formclass =xml.getBeanClass();
		Object bean =BeanUtil.fullBean(formclass, request);
		String actionClass = xml.getActionClass();
		Object action =null;
		String url ="";
		try {
			Class clazz = Class.forName(actionClass);
			action =  clazz.newInstance();	
			Method method = clazz.getMethod(xml.getMothod(),bean.getClass());
		    url = (String) method.invoke(action, bean);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		RequestDispatcher dis= request.getRequestDispatcher(xml.getActionForward().get(url));
		dis.forward(request, response);
	}
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,IOException{
		this.doGet(request, response);
	}
    private String getPath(String path) {

		return path.split("\\.")[0];
	}
}
